# -*- coding: utf-8 -*-

# Create your views here.

from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.db.models import ProtectedError

from ..models import Rubros
from ..forms import RubrosForm


# RUBROS

def agregar_rubros(request):
    """Agrega rubro"""
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = RubrosForm(request.POST)
            if form.is_valid():
                registro = form.save()
                return HttpResponseRedirect('/rubros/agregar/')
        else:
            form = RubrosForm()
        todo = Rubros.objects.all()
        variables = RequestContext(request, {
            'form': form,
            'todo': todo,
        })
        return render_to_response('agregar_rubros.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def editar_rubros(request, rubroid):
    """Edita rubro"""
    if request.user.is_authenticated():
        r = Rubros.objects.get(pk=rubroid)
        if request.method == 'POST':
            form = RubrosForm(request.POST, instance=r)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/rubros/agregar/')
        else:
            form = RubrosForm(instance=r)
        variables = RequestContext(request, {'form': form})
        return render_to_response('editar_rubros.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def check_rubros(request, rubroid):
    """Confirmar antes de eliminar"""
    if request.user.is_authenticated():
        rubro = Rubros.objects.get(pk=rubroid)
        variables = RequestContext(request, {
            'rubro': rubro,
        })
        return render_to_response('borrado_rubros.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def borrar_rubros(request, rubroid):
    """Elimina rubro"""
    if request.user.is_authenticated():
        r = Rubros.objects.get(pk=rubroid)
        try:
            r.delete()
        except ProtectedError:
            variables = RequestContext(request, {'mensaje': 'NO se puede eliminar porque tiene gastos asociados'})
            return render_to_response('error.html', variables)
        return HttpResponseRedirect('/rubros/agregar/')
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)
